﻿using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using HandyControl.Controls;
using Hardcodet.Wpf.TaskbarNotification;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.RichTextBox.Themes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
 
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using WatchDog;
using WatchDog.WatchItemManages;
using WatchDogApp.Service;
using WatchDogApp.Windows;
using static System.Windows.Forms.LinkLabel;

namespace WatchDogApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public IServiceProvider Service { get; private set; }
        public IConfiguration Configuration { get; private set; }

        public new static App Current => Application.Current as App;

        // public static IHost Host { get; private set; }
       
        public App()
        {
            string strAssemblyFilePath = Assembly.GetExecutingAssembly().Location;
            string strAssemblyDirPath = Path.GetDirectoryName(strAssemblyFilePath);

            WatchDog.Serilog.loggingLevelSwitch.MinimumLevel = LogEventLevel.Debug;
 
            Log.Logger = new LoggerConfiguration()
            .MinimumLevel.ControlledBy(WatchDog.Serilog.loggingLevelSwitch)
            //.WriteTo.RichTextBox( , theme: RichTextBoxConsoleTheme.Grayscale)
           //.WriteTo.Sink(s)
           .WriteTo.File(strAssemblyDirPath + "/Logs/control-.log",
           rollingInterval: RollingInterval.Day,
           retainedFileTimeLimit: TimeSpan.FromDays(7),
           outputTemplate: "{Timestamp:HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
           fileSizeLimitBytes: 5242880)
           .CreateLogger();


            var builder = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            Configuration = builder.Build();

            var serviceProvider = ConfigureServices();
            //serviceProvider.AddSingleton(s);
            Service = serviceProvider.BuildServiceProvider();

            WatchDog.Serilog.StartReceiveLog();
            //Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
            //    .ConfigureServices((context, services) =>
            //    {
            //        ConfigureServices(services);

            //    })
            //    .ConfigureLogging((context, logging) =>
            //    {
            //        logging.AddConfiguration(context.Configuration.GetSection("Logging"));
            //        //logging.AddDebug();
            //    })
            //    .Build();


        }

        private static ServiceCollection ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddSingleton<BackgroundTask>();
            services.AddSingleton<TaskbarIcon>();
            services.AddSingleton<MainWindow>();

            services.AddSingleton<MainWindowViewModel>();
            services.AddSingleton<NotifyIconViewModel>();

            services.AddSingleton<WatchItemManage>();
            return services;
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            //await Host?.StartAsync();

            //此处也可以在xaml中配置
            var window = Service.GetRequiredService<MainWindow>();
            window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            //window.DataContext = Service.GetRequiredService<MainWindowViewModel>();
            window.Show();

            var taskbarNotification = Service.GetService<BackgroundTask>().TaskbarNotification;
            taskbarNotification.ContextMenu = (ContextMenu)FindResource("TaskbarIconContextMenuControlKey");
            taskbarNotification.DoubleClickCommand = new RelayCommand(() =>
            {
                if (App.Current.MainWindow.IsVisible == false)
                {
                    App.Current.MainWindow.Show();
                }

                if (App.Current.MainWindow.WindowState == WindowState.Minimized)
                {
                    SystemCommands.RestoreWindow(App.Current.MainWindow);
                }

                if (App.Current.MainWindow.IsActive == false)
                {
                    App.Current.MainWindow.Activate();
                }


                App.Current.MainWindow.Topmost = true;
            });

            await Task.CompletedTask;

            base.OnStartup(e);
        }
        protected override async void OnExit(ExitEventArgs e)
        {
            //await Host?.StopAsync();
            Service.GetService<BackgroundTask>().TaskbarNotification.Dispose();
            base.OnExit(e);
            await Task.CompletedTask;
        }

    }
 
}
